<template>
    <el-card style="height:80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名：">
                <el-input placeholder="请您输入搜索用户名" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="search" type="primary" size="default" :disabled="keyword ? false : true">搜索</el-button>
                <el-button type="primary" size="default" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin:10px 0px;">
        <el-button type="primary" size="default" @click="addUser">添加用户</el-button>
        <el-button type="primary" size="default" :disabled="selectIdArr.length ? false : true"
            @click="deleteSelectUser">批量删除</el-button>
        <!-- table展示用户信息 -->
        <el-table @selection-change="selectChange" style="margin:10px 0px;" border :data="userArr">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column type="index" label="#" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" align="center"></el-table-column>
            <el-table-column prop="username" label="用户名字" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="name" label="用户名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="roleName" label="用户角色" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px">
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm :title="`您确定要删除${row.username}吗？`" width="260px" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination @size-change="handler" @current-change="getHasUser" v-model:current-page="pageNo"
            v-model:page-size="pageSize" :page-sizes="[5, 7, 9]" :background="true"
            layout=" prev, pager, next, jumper,->,sizes,total " :total="total" />
    </el-card>
    <!-- 抽屉结构-添加新账号和修改已有账号 -->
    <el-drawer v-model="drawer">
        <template #header>
            <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userParams" :rules="rules" ref="formRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请您输入用户姓名" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请您输入用户昵称" v-model="userParams.name"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                    <el-input placeholder="请您输入用户密码" v-model="userParams.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </div>
        </template>
    </el-drawer>
    <!-- 抽屉结构-用于给已有账号分配职位 -->
    <el-drawer v-model="drawer1">
        <template #header>
            <h4>分配角色(职位)</h4>
        </template>
        <template #default>
            <el-form>
                <el-form-item label="用户姓名">
                    <el-input v-model="userParams.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="职位列表">
                    <el-checkbox @change="handleCheckAllChange" v-model="checkAll"
                        :indeterminate="isIndeterminate">全选</el-checkbox>
                    <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="(role, index) in allRole" :key="index" :label="role">{{ role.roleName
                        }}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer1 = false">取消</el-button>
                <el-button type="primary" @click="confirmClick">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue';
import { reqSlectUser, reqRemoveUser, reqUserInfo, reqAddOrUpdateUser, reqAllRole, reqSetUserRole } from '@/api/acl/user/index'
import { ElMessage } from 'element-plus';
import useLayOutSettingStore from '@/store/modules/setting';
const settingStore = useLayOutSettingStore()
let pageNo = ref(0)
let pageSize = ref(5)
let total = ref(0)
// 存储全部用户的信息
let userArr = ref([])
// 控制新增账号或者修改账号抽屉的显示与隐藏
let drawer = ref(false)
// 控制分配角色抽屉的显示与隐藏
let drawer1 = ref(false)
// 收集全选按钮的数据
const checkAll = ref(false)
// 控制顶部全选复选框不确定样式
const isIndeterminate = ref(true)
// 获取form组件实例
let formRef = ref()
// 存储全部职位的数据
let allRole = ref<any>([])
// 当前已有的用户职位
let userRole = ref<any>([])
// 批量删除用户的数据
let selectIdArr = ref([])
// 用户搜索输入的关键字
let keyword = ref('')
// 收集用户信息的数据
let userParams = reactive<any>({
    username: '',
    name: '',
    password: ''
})
onMounted(() => {
    getHasUser()
})
// 获取用户信息的方法
const getHasUser = async (pager = 1) => {
    pageNo.value = pager
    let result = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
    if (result.code == 200) {
        userArr.value = result.data.records
        total.value = result.data.total
    }
}
// 分页器下拉菜单的回调
const handler = () => {
    getHasUser()
}
// 添加用户按钮的回调
const addUser = () => {
    drawer.value = true
    Object.assign(userParams, {
        id: 0,
        username: '',
        name: '',
        password: ''
    })
    // 清除上一次的错误的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
        formRef.value.clearValidate('password')
    })
}
// 更新已有的用户按钮的回调
const updateUser = (row: any) => {
    drawer.value = true
    Object.assign(userParams, row)
    // 清除上一次的错误的提示信息
    nextTick(() => {
        formRef.value.clearValidate('username')
        formRef.value.clearValidate('name')
    })
}
// 抽屉保存按钮的回调
const save = async () => {
    // 表单校验通过再发请求
    await formRef.value.validate()
    let result: any = await reqAddOrUpdateUser(userParams)
    if (result.code == 200) {
        drawer.value = false
        ElMessage({ type: 'success', message: userParams.id ? '更新成功' : '添加成功' })
        // getHasUser(userParams.id ? pageNo.value : 1)
        // 浏览器自动刷新一次
        window.location.reload()
    } else {
        drawer.value = false
        ElMessage({ type: 'error', message: userParams.id ? '更新失败' : '添加失败' })
    }
}
// 取消按钮的回调
const cancel = () => {
    drawer.value = false
}


// 校验用户名字的回调函数
const validatorUsername = (_: any, value: any, callBack: any) => {
    if (value.trim().length >= 5) {
        callBack()
    } else {
        callBack(new Error('用户名字至少五位'))
    }
}
// 校验昵称的回调函数
const validatorname = (_: any, value: any, callBack: any) => {
    if (value.trim().length >= 5) {
        callBack()
    } else {
        callBack(new Error('用户昵称至少五位'))
    }
}
//  校验密码的回调函数
const validatorPassword = (_: any, value: any, callBack: any) => {
    if (value.trim().length >= 6) {
        callBack()
    } else {
        callBack(new Error('用户密码至少六位'))
    }
}

// 表单校验的规则对象
const rules = {
    username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
    name: [{ required: true, trigger: 'blur', validator: validatorname }],
    password: [{ required: true, trigger: 'blur', validator: validatorPassword }]
}

// 分配角色按钮的回调
const setRole = async (row: any) => {
    // 存储已有的用户信息
    Object.assign(userParams, row)
    let result = await reqAllRole(userParams.id)
    if (result.code == 200) {
        allRole.value = result.data.allRolesList
        userRole.value = result.data.assignRoles
        drawer1.value = true
    }
}
// 顶部全选复选框的change事件
const handleCheckAllChange = (val: any) => {
    userRole.value = val ? allRole.value : []
    isIndeterminate.value = false
}
// 底部全部复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
    checkAll.value = value.length === allRole.value.length
    isIndeterminate.value = value.length !== allRole.value.length
}
// 分配职位按钮的确定按钮回调
const confirmClick = async () => {
    // 收集数据
    let data = {
        userId: userParams.id,
        roleIdList: userRole.value.map((item: any) => item.id)
    }
    let result = await reqSetUserRole(data)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '分配职务成功' })
        drawer1.value = false
        getHasUser(pageNo.value)
    } else {
        ElMessage({ type: 'error', message: '分配职务失败' })
        drawer1.value = false
    }
}
// 删除某一个用户的回调
const deleteUser = async (userId: any) => {
    let result = await reqRemoveUser(userId)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({ type: 'error', message: '删除失败' })
    }
}
// table复选框勾选触发的事件
const selectChange = (value: any) => {
    selectIdArr.value = value
}
// 批量删除按钮的回调
const deleteSelectUser = async () => {
    // 整理批量删除的参数
    let idsList = selectIdArr.value.map((item: any) => {
        return item.id
    })
    let result = await reqSlectUser(idsList)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
    } else {
        ElMessage({ type: 'error', message: '删除失败' })
    }
}
// 搜索按钮的回调
const search = () => {
    getHasUser()
    keyword.value = ''
}
// 重置按钮的回调
const reset = () => {
    settingStore.refsh = !settingStore.refsh
}
</script>

<style scoped lang="scss">
.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>